__author__ = 'yejinlei_cn@qq.com'

import importlib

class pyFactoryMethod():
    ''' factory method '''

    def __new__(cls, modulename, classname, *args, **kwargs):
        '''Create a object

        :type modulename: module's name
        :type classname: class's name or class
        :rtype: user-defined object
        '''
        if isinstance(modulename, str):
            _module = importlib.import_module(modulename)
        else:
            raise ImportError
            return

        if isinstance(classname, str):
            _class = getattr(_module, classname)
        elif isinstance(classname, type):
            _class = classname
        else:
            raise AttributeError
            return

        return _class(*args, **kwargs)

#test
class TEST1:
    def __init__(self, var1, var2):
        self.var1 = var1
        self.var2 = var2

    def show(self):
        print(self.var1)
        print(self.var2)

class TEST2:
    def __init__(self, var):
        self.var1 = var

    def show(self):
        print(self.var1)

if __name__ == '__main__':
    t1 = pyFactoryMethod(__name__, 'TEST1', 'hello', 'yejinlei!')
    t1.show()

    t2 = pyFactoryMethod(__name__, 'TEST2', 'hi!')
    t2.show()
